package com.hulushuju.core.net.http.okhttp;

import com.hulushuju.core.net.ContentType;
import com.hulushuju.core.net.exception.HttpException;
import com.hulushuju.core.net.exception.UnSupportedTypeException;
import com.hulushuju.core.net.http.HttpResponse;
import com.hulushuju.core.util.FileManager;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-05-29
 * @Desc: 保存请求拦截器
 */
public class StoreRequestInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //写入文件内容
        StringBuilder contents = new StringBuilder();

        //获取当前日期
        String currentDate = null;//DateManager.formatDate(null);
        contents.append("RequestTime:").append(currentDate).append("\n");

        Request request = chain.request();
        long startTime = System.nanoTime();

        //处理请求
        Response response = chain.proceed(request);
        HttpResponse httpResponse = new OkHttpResponseImpl(response);
        try {
            //读取内容类型
            MediaType mediaType = response.body().contentType();
            String type = mediaType.type();
            //只记录文本内容
            if (!ContentType.TEXT.equals(type)) {
                throw new UnSupportedTypeException("记录请求只支持文本类型");
            }

            //请求参数
            String url = request.url().toString();
            contents.append("URL:").append(url).append("\n");
            //请求头
            String headers = request.headers().toString();
            contents.append("RequestHeaders:").append(headers).append("\n");
            //请求方法
            String method = request.method();
            contents.append("RequestMethod:").append(method).append("\n");
            try {
                //请求体参数
                String param = request.body().toString();
                contents.append("RequestParam:").append(param).append("\n");
            } catch (NullPointerException ignore) {
            }
            long finishTime = System.nanoTime();
            //请求消耗时间
            double consumeTime = (finishTime - startTime) / 1e6d;
            contents.append("ConsumeTime:").append(consumeTime).append("ms").append("\n");

            //响应参数,获取返回文本
            String body = httpResponse.getContent(String.class);
            contents.append("ResponseBody:").append("\n").append(body).append("\n");

            //写入本地
            FileManager.writeNew(null, contents.toString(), mediaType.subtype());
        } catch (NullPointerException e) {
            //todo 写入日志
            e.printStackTrace();
        } catch (HttpException ignore) {
        }

        //响应参数
        return response;
    }
}
